import { FlowModuleJumpType, JumpPageTypeMap } from "@/types/enum"
import { requestIsFullfilled } from "@/utils/request"
import { navigation, navigationPlugin } from "@/utils/router"
import { withStore } from "@/store/index"
import { pageMapper, pageMapperCommunity } from "@/constants/pageMap"
import { patchExtra } from "@/store/actions/auth"

/**
 * get app launch options
 */
export const getLaunchOptions = (): IAppLaunchOptions => {
  const launchOptions = Taro.getLaunchOptionsSync() || {}
  return launchOptions as IAppLaunchOptions
}
/**
 * get current page info, includes `route` & `options` & `Page`
 */
export const getCurrentPageInfo = (): ICurrentPageInfo => {
  const pages = Taro.getCurrentPages()
  if (pages.length < 1) return {}
  const currentPage = pages[pages.length - 1]
  return {
    route: currentPage.route,
    options: currentPage.options as Recordable,
    currentPage: currentPage
  }
}

/** cache request data */
export function withRequestCache<
  R,
  O extends Taro.request.SuccessCallbackResult<
    IApiRelative.IResSchema<R>
  > = Taro.request.SuccessCallbackResult<IApiRelative.IResSchema<R>>
>(request: () => Promise<O>, key: string) {
  return async function (): Promise<O> {
    // @ts-ignore
    if (withRequestCache.cache) {
      // @ts-ignore
      const cached = withRequestCache.cache.get(key)
      if (cached) return cached
    }
    const res = await request()
    if (requestIsFullfilled(res)) {
      // @ts-ignore
      withRequestCache.cache = withRequestCache.cache || new Map<string, O>()
      // @ts-ignore
      withRequestCache.cache.set(key, res)
    }
    return res
  }
}
/** 处理后台菜单配置模块跳转 */
export function handleBlockNavigation(
  block?: Pick<
    IApiRelative.IGetIndexData.MenuItem,
    "jumpPageId" | "jumpPageType" | "jumpType" | "jumpUrl"
  >,
  extraQuery?: Recordable<string | number>
) {
  if (!block) return
  const { jumpPageId, jumpPageType, jumpType, jumpUrl } = block
  if (jumpType === FlowModuleJumpType.Miniprogram) {
    const meta = JumpPageTypeMap.get(jumpPageType)
    if (meta) {
      const query: Partial<PrimaryKey<number>> = {
        ...extraQuery
      }
      if (jumpPageId) {
        query.id = jumpPageId
      }
      navigation(meta.pagePath, query, meta.isTabbarPage ? "switchTab" : "navigateTo")
    }
  } else if (jumpType === FlowModuleJumpType.Account) {
    console.info("跳转公众号", jumpUrl)
    navigation(pageMapper.external, { url: jumpUrl })
  } else if (jumpType === FlowModuleJumpType.MiniprogramPlugin) {
    navigationPlugin(jumpUrl)
  }
}
/**
 * 处理授权相关处理
 * @description 授权头像昵称：当用户授权手机号却没有配置头像昵称时，用户评论或发笔记会跳一次弹窗，用户如果再次取消不影响他发笔记发内容，下次再点接着跳弹窗
 * @description 主要有下面几个场景需要用户相关授权:
 * 1、发布笔记/短评入口(需要手机号，头像，昵称)

    2、笔记/话题：评论(需要手机号，头像，昵称)、收藏(需要手机号)

    3、关注用户(需要手机号)

    4、个人主页部分按钮(需要手机号)
 */
export function authActionHandler(fulfilledFn: IFn, options?: IAuthActionHandlerOptions) {
  options = Object.assign({}, { avatarAndNickname: true, mobile: true }, options)
  if (!options.mobile && !options.avatarAndNickname) {
    fulfilledFn()
    return
  }
  const store = withStore()
  const { userInfo: authInfo, extra: authExtra } = store.getState().auth
  if (options.mobile && !authInfo.mobile) {
    navigation(pageMapperCommunity.AuthLogin)
    return
  }
  if (options.avatarAndNickname) {
    if ((authInfo.headImage && authInfo.nickName) || authExtra.authModalCanceled) {
      fulfilledFn()
    } else {
      store.dispatch(
        patchExtra({
          showAuthModal: true
        })
      )
    }
    return
  }
  fulfilledFn()
}
